package com.azzcs.myrpc.client;

import com.azzcs.myrpc.request.RpcEncoder;
import com.azzcs.myrpc.request.RpcRequest;
import com.azzcs.myrpc.serializer.Serializer;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @Author: wzg
 * @Date: 2021/1/22 下午5:07
 */
public class RpcClient {
    @Value("${rpc.client.host}")
    private String host;
    @Value("${rpc.client.port}")
    private int port;

    @Autowired
    private Serializer serializer;

    private static ExecutorService executor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());

    public RpcClient() {

    }

    public <T> T build(Class<T> clazz) {
        return (T) Proxy.newProxyInstance(this.getClass().getClassLoader(),
                new Class[]{clazz},
                new MyInvocationHandler());
    }

    private class MyInvocationHandler implements InvocationHandler {

        @Override
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            ClientHandler<String> handler = new ClientHandler();
            EventLoopGroup group = new NioEventLoopGroup();
            Bootstrap b = new Bootstrap();
            b.group(group)
                    .channel(NioSocketChannel.class)
                    .option(ChannelOption.TCP_NODELAY, true)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        public void initChannel(SocketChannel ch) throws Exception {
                            ChannelPipeline p = ch.pipeline();
                            p.addLast(new StringDecoder());
                            p.addLast(new RpcEncoder(RpcRequest.class,serializer));
                            p.addLast(handler);
                        }
                    });
            try {
                b.connect(host, port).sync();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            Class<?> clazz = method.getDeclaringClass();
            String className = clazz.getName();
            String methodName = method.getName();
            Class<?>[] parameterTypes = method.getParameterTypes();

            RpcRequest request = new RpcRequest();
            request.setClassName(className);
            request.setMethodName(methodName);
            request.setParameterTypes(parameterTypes);
            request.setParameters(args);

            handler.setParameter(request);

            return executor.submit(handler).get();

        }
    }

}
